﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using ESoft.RabbitMQ;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;

namespace ESoft.RabbitMQ
{
    /// <summary>
    /// Rabbit工厂
    /// </summary>
    internal class RabbitFactory : IRabbitFactory
    {
        private static volatile IConnection conn = null;
        private readonly RabbitMQOption _rabbitMQOption;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="options"></param>
        public RabbitFactory(IOptions<RabbitMQOption> options)
        {
            _rabbitMQOption = options.Value;
        }

        private IConnection GetConnection()
        {
            lock (this)
            {
                if (conn == null || !conn.IsOpen)
                {
                    ConnectionFactory factory = new ConnectionFactory
                    {
                        UserName = _rabbitMQOption.UserName,
                        Password = _rabbitMQOption.Password,
                        VirtualHost = _rabbitMQOption.VirtualHost,
                        HostName = _rabbitMQOption.HostName,
                        Port = _rabbitMQOption.Port,
                    };
                    conn = factory.CreateConnection();
                }
            }

            return conn;
        }

        /// <summary>
        /// 创建管道
        /// </summary>
        /// <returns></returns>
        public IModel CreateChannel()
        {
            var connection = GetConnection();
            var channel = connection.CreateModel();
            return channel;
        }
    }
}
